package com.helen.mybatis.executor;

import com.google.common.collect.Lists;
import com.helen.mybatis.configration.MappedStatement;
import com.helen.mybatis.mapping.BoundSql;
import com.helen.mybatis.mapping.GenericTokenParser;
import com.helen.mybatis.mapping.ParameterMapping;
import com.helen.mybatis.mapping.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author helenlee
 * @date 2020/4/8
 */
public class SimpleExecutor implements Executor{
    @Override
    public <E> List<E> query(MappedStatement ms, Object[] parameter) throws Exception {
        // 1. 获取连接
        Connection connection = ms.getConfiguration().getDataSource().getConnection();

        // 2. 解析sql
        String sql = ms.getSql();
        // 解析SQL
        BoundSql boundsql =  getBoundSql(sql);
        // 获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundsql.getSqlText());
        List<ParameterMapping> parameterMappingList = boundsql.getParameterMappingList();
        Class<?> paramType = ms.getParamType();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            Field field = paramType.getDeclaredField(parameterMapping.getContent());
            // 申请访问权限
            field.setAccessible(true);
            Object param = field.get(parameter[0]);
            preparedStatement.setObject(i+1,param);
        }

        ResultSet resultSet = preparedStatement.executeQuery();
        Class<?> resultType = ms.getResultType();
        ArrayList<Object> resultList = Lists.newArrayList();
        while (resultSet.next()){
            // 根据返回值实例化对象
            Object instance = resultType.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++){
                // 字段名称
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(instance,value);
            }
            resultList.add(instance);
        }


        return (List<E>) resultList;
    }


    @Override
    public int update(MappedStatement ms, Object[] parameter) throws Exception {
        // 1. 获取连接
        Connection connection = ms.getConfiguration().getDataSource().getConnection();

        // 2. 解析sql
        String sql = ms.getSql();
        // 解析SQL
        BoundSql boundsql =  getBoundSql(sql);
        // 获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundsql.getSqlText());
        List<ParameterMapping> parameterMappingList = boundsql.getParameterMappingList();
        Class<?> paramType = ms.getParamType();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            Field field = paramType.getDeclaredField(parameterMapping.getContent());
            // 申请访问权限
            field.setAccessible(true);
            Object param = field.get(parameter[0]);
            preparedStatement.setObject(i+1,param);
        }

        return preparedStatement.executeUpdate();

    }

    private BoundSql getBoundSql(String sql) {
        //标记处理类：配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String parseSql = genericTokenParser.parse(sql);
        //#{}里面解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parseSql,parameterMappings);
        return boundSql;
    }

}
